import { ref, computed, onMounted, watch } from "vue";
import ToolAction from "@/tool/http/tool-action.js";
import toolCache from "@/tool/tool-cache";

let apiTag = ToolAction.init("common_tag");

export default function useTags(defaultCheckTagIds = []) {
  const tags = ref([]);
  defaultCheckTagIds = defaultCheckTagIds || [];

  onMounted(() => {
    initList();
  });

  const initList = async () => {
    let comTags = await toolCache.cache("com-tags", async () => {
      let res = await apiTag.list();
      res
        .filter((item) => defaultCheckTagIds.includes(item.id))
        .forEach((item) => (item.checked = true));
      return res;
    }, 3 * 1000);
    return (tags.value = comTags);
  };

  const remove = (id) => {
    apiTag.remove(id).then((res) => {
      tags.value = tags.value.filter((tag) => tag.id !== id);
    });
  };

  const add = (name) => {
    if (!name || tags.value.find((item) => item.name === name)) {
      return;
    }
    apiTag
      .sync({
        name,
      })
      .then((res) => {
        tags.value = [
          ...tags.value,
          {
            name,
          },
        ];
      });
  };

  const transformName = (ids = []) => {
    return tags.value
      .filter((item) => ids.includes(item.id))
      .map((item) => item.name);
  };

  return {
    tags,
    remove,
    add,
    transformName,
    initList,
  };
}
